import re

from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import check_token
from users.models import User

'''
逻辑　请求方式　post
参数　　手机号　密码　短信验证码　openid
进行校验　　序列化器的选择　　
进行保存
１　先进行校验短信验证码　
２　进行验证openid
３　判断用户是否存在
４　存在　是否以前绑定过
５　没有绑定　从新绑定　
６　绑定过　校验密码是否正确
７　不存在　那么进行创建用户
８　进行create 的方法
'''


class CodeQQAPIViewSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    #  进行多个字段的验证
    def validate(self, attrs):
        mobile = attrs.get('mobile')
        if not re.match(r'1[3-9]\d{9}',mobile):
            raise serializers.ValidationError('手机号格式不正确')

        access_token = attrs.get('access_token')

        openid = check_token(access_token)
        if not openid:
            raise serializers.ValidationError('过期')
        self.openid = openid
        sms_code = attrs.get('sms_code')

        from django_redis import get_redis_connection

        redis_conn = get_redis_connection('code')
        try:
            redis_sms_code = redis_conn.get('sms_%s'% mobile)
        except Exception:
            raise serializers.ValidationError('短信验证码失效')

        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码输入有误')
        try:

            user = User.objects.get(mobile = mobile)

        except User.DoesNotExist:
            pass

        else:
            password = attrs.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
            self.user = user

        return attrs

    def create(self, validated_data):
        user = self.user,
        openid = self.openid

        if not user:
            self.user.objects.create(
                username=validated_data.get('moblie'),
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password')


            )
            self.user.set_password(validated_data.get('password'))

        OAuthQQUser.object.create(
            user = user,
            openid = openid

        )

        return user










